<?php

namespace App\Http\Controllers\Company;

use App\Jobs\PersonalInterviewPush;
use App\Models\Common\CollArea;
use App\Models\Common\CollOption;
use App\Models\Company\BuyResume;
use App\Models\Company\ResumeFavorite;
use App\Models\Personal\ResumeSend;
use Config;
use App\Facades\Style;
use App\Http\Controllers\Company\CommonController;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use App\Models\Personal\Resume;
use App\Models\Personal\Interview;
use App\Models\Company\CompanyJob;

class InterviewController extends CommonController{

    /**
     * 收到应聘简历
     * @param Request $request
     * @return mixed
     */
    public function message(Request $request){
        $user = auth()->guard('company')->user();
        //获取面试通知记录
        $relist = DB::table('interview as log')
            ->join('resume as t1', 'log.resume_id', '=', 't1.id')
            ->join('company_job as t2', 'log.job_id', '=', 't2.id')
            ->select(
                'log.id', 'log.status', 'log.updated_at', 't1.name', 't1.sex', 't1.birthday',
                't1.education', 't1.homeaddress', 't2.job_title', 'log.job_id', 'log.resume_id'
            )
            ->where('log.company_uid', $user->uid)
            ->where(function($query) use ($request){
                if(strlen($request->keyWord) > 0){
                    $query->where('t2.job_title', 'like', '%' . $request->keyWord . '%')->orWhere('t1.name', 'like', '%' . $request->keyWord . '%');
                }
            })
            ->where(function($query) use ($request){
                if(strlen($request->status) > 0){
                    $query->where('log.status', $request->status);
                }
            })
            ->where('log.status', '!=', 4)
            ->orderBy('created_at', 'DESC')
            ->paginate(20);
        foreach($relist as $v){
            switch($v->sex){
                case "1":
                    $v->cnsex = '男';
                    break;
                case "2":
                    $v->cnsex = '女';
                    break;
                default:
                    $v->cnsex = '';
            }
            $v->education = CollOption::getOptionName($v->education, 'education');
            $v->homeaddress = CollArea::getAreaName($v->homeaddress);
            $v->birthday = birthday($v->birthday);
        }

        $status = $request->status;

        return Style::view('company.interviewManage', compact('relist', 'status'));
    }

    /**
     * 删除简历库
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function destroy(Request $request){

        $user = auth()->guard('company')->user();
        $input['status'] = 4;
        if(!empty($request->id)){
            Interview::where('company_uid', $user->uid)->where('id', $request->id)->update($input);
        }elseif(is_array($request->selected_id)){
            Interview::where('company_uid', $user->uid)->whereIn('id', $request->selected_id)->update($input);
        }
        return back()->withInput()->with('info', "已删除!");
    }

    /**
     * 放入人才库
     * @param Request $request
     */
    public function toFavorite(Request $request){
        $user = auth()->guard('company')->user();
        if(is_array($request->selected_id)){
            $browseJob = Interview::select('resume_id', 'job_id')->where('company_uid', $user->uid)->whereIn('id', $request->selected_id)->get();
            foreach($browseJob as $v){
                $favorite = ResumeFavorite::select('id')->where('uid', $user->uid)->where('status', '!=', 4)->where("resume_id", $v->resume_id)->first();
                if(!empty($favorite->id)){
                    $favorite->updated_at = date('Y-m-d H:i:s');
                    $favorite->status = 0;
                    $favorite->save();
                }else{
                    $favorite = new ResumeFavorite;
                    $favorite->uid = $user->uid;
                    $favorite->resume_id = $v->resume_id;
                    $favorite->job_id = $v->job_id;
                    $favorite->status = 0;
                    $favorite->save();
                }
            }
            return back()->withInput()->with('info', "已将简历放入人才库!");
        }
    }

    /**
     * 面试通知发送
     * @param Request $request
     * @return mixed
     */
    public function setInterView(Request $request){
        $input = $request->only('jobId', 'resumeId', 'inpstart', 'jobnote');
        //企业登录
        $user = auth()->guard('company')->user();
        if(!empty($user->uid) && $user->resumeNumber() > 0){//简历数是不是为0
            if(!empty($request->jobId)){
                //查询jobid 是否是该企业用户发布
                $companyJob = CompanyJob::select('com_id')->where("id", $request->jobId)->where('uid', $user->uid)->first();
                $reSume = Resume::select('uid')->where('id', $request->resumeId)->first();
                if(!empty($companyJob) && !empty($reSume)){

                    $data['company_uid'] = $user->uid;//企业uid
                    $data['com_id'] = $companyJob->com_id;//所属企业comid
                    $data['personal_uid'] = $reSume->uid;//人才UID
                    $data['resume_id'] = $request->resumeId;//所属简历id
                    $data['job_id'] = $request->jobId;//招聘职位id
                    $data['interview_time'] = $request->inpstart;//邀请面试时间
                    $data['status'] = 0;//面试状态
                    $data['remark'] = $request->jobnote;//备注
                    $nowTime = date('Y-m-d H:m:s');
                    $data['created_at'] = $nowTime;//创建时间
                    $data['updated_at'] = $nowTime;//更新时间

                    //简历是不是被购买
                    $BuyResume = BuyResume::where('company_uid', $user->uid)->where('resume_id', $request->resumeId)->first();
                    if(empty($BuyResume)){
                        //在会员期内投递过简历
                        $ResumeSend = ResumeSend::select('created_at')->where("resume_id", $request->resumeId)->where('company_uid', $user->uid)->first();
                        if(empty($ResumeSend)){
                            //无投递过简历&&无购买过=》判断简历数
                            if($user->resumeNumber() > 0){
                                if($user->resumeDeduct(1)){
                                    $buyResume['company_uid'] = $user->uid;
                                    $buyResume['personal_uid'] = $reSume->uid;
                                    $buyResume['resume_id'] = $request->resumeId;
                                    $buyResume['com_id'] = $companyJob->com_id;
                                    BuyResume::create($buyResume);
                                }
                            }
                        }
                    }

                    //查看面试状态
                    $Interview = Interview::select('id', 'status', 'created_at')->where('company_uid', $user->uid)
                        ->where('com_id', $companyJob->com_id)->where('personal_uid', $reSume->uid)
                        ->where('resume_id', $request->resumeId)->where('job_id', $request->jobId)
                        ->orderBy('created_at', 'desc')->first();

                    if(!empty($Interview)){

                        if($Interview->status == 0){//未查看，24小时内，可以修改

                            if($this->timediff($Interview->created_at) > (3600 * 24)){//超过一天

                                if(!empty($request->jobId)){
                                    $interview = Interview::create($data);
                                    $this->messagePush($interview);
                                    return response()->json(['status' => '0', 'msg' => '面试邀请发送成功！']);
                                }

                            }else{
                                //一天内，不能重复发送
                                return response()->json(['status' => '1', 'msg' => '您今天已邀请过了！']);
                            }

                        }elseif($Interview->status == 1){//对方已查看

                            return response()->json(['status' => '0', 'msg' => '您的面试邀请对方已查看！']);

                        }elseif($Interview->status == 2){//对方已接受邀请

                            return response()->json(['status' => '0', 'msg' => '对方已接受您的面试邀请！']);

                        }else{//对方已婉拒您的面试邀请

                            if(!empty($request->jobId)){
                                $interview = Interview::create($data);
                                $this->messagePush($interview);
                                return response()->json(['status' => '0', 'msg' => '面试邀请发送成功！']);
                            }

                        }

                    }else{//没有则加一条面试通知

                        if(!empty($request->jobId)){
                            $interview = Interview::create($data);
                            $this->messagePush($interview);
                            return response()->json(['status' => '0', 'msg' => '面试邀请发送成功！']);
                        }
                    }
                }
            }else{
                return response()->json(['status' => '1', 'msg' => '未选择面试职位！']);
            }
        }else{
            return response()->json(['status' => '1', 'msg' => '您的简历数不够，不能发送面试邀请！']);
        }
    }

    /**
     * 消息推送
     * @param $resumeId
     */
    public function messagePush($data){
        $job = (new PersonalInterviewPush($data));
        $this->dispatch($job);
    }


    //分配
    public function distributionJob(Request $request){
        $user = auth()->guard('company')->user();
        $input = $request->only("resume_id", 'job_id');
        if(!empty($user)){
            $resumeFavorite = ResumeFavorite::where("uid", $user->uid)->where('resume_id', $input['resume_id'])
                ->where('job_id', '!=', '0')->orderBy('updated_at','desc')->first();
            if(empty($resumeFavorite)){
                $input['uid'] = $user->uid;
                $input['status'] = 0;
                ResumeFavorite::create($input);
                return response()->json(['status' => 0, 'msg' => '分配岗位成功!']);
            }else{
                ResumeFavorite::where("id", $resumeFavorite->id)->update(["job_id" => $request->job_id, "status" => 0]);
                return response()->json(['status' => 0, 'msg' => '更新岗位成功!']);
            }
        }else{
            return response()->json(['status' => 0, 'msg' => '请先登录，在分配岗位！']);
        }
    }


    /**
     * 前台纳入人才库
     * @param Request $request
     * @return mixed
     */
    public function insertPersonnelLibrary(Request $request){
        $input = $request->only("resume_id", 'job_id');
        //查找人才是否已被纳入人才库
        $haveFavorite = ResumeFavorite::where("uid", auth()->guard('company')->user()->uid)->where("resume_id", $request->resume_id)
            ->first();//->where("job_id",$request->job_id)
        if($haveFavorite){
            $status = 0;
            ResumeFavorite::where("uid", auth()->guard('company')->user()->uid)->where("resume_id", $request->resume_id)->update(["job_id" => $request->job_id, "status" => 0]);
        }else{
            $status = 0;
            //添加到人才库
            $input['uid'] = auth()->guard('company')->user()->uid;
            $input['status'] = 0;
            ResumeFavorite::create($input);
        }
        $msg = "分配成功！";
        return response()->json(['status' => $status, 'msg' => $msg]);
    }

    /**
     * 取消纳入人才库
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function delPersonnelLibrary(Request $request){
        $request->only("resume_id", 'job_id');
        $updateFavorite = ResumeFavorite::where("uid", auth()->guard('company')->user()->uid)->where("resume_id", $request->resume_id)->update(["job_id" => 0]);
        if($updateFavorite){
            $status = 0;
            $msg = "已取消！";
        }else{
            $status = 1;
            $msg = "取消失败，请稍候再试！";
        }
        return response()->json(['status' => $status, 'msg' => $msg]);
    }

    /**
     * 时间差
     * @param $time
     * @return int
     */
    public function timediff($time){
        $zero1 = strtotime(date("Y-m-d H:i:s", time()));
        $zero2 = strtotime($time);
        $time_c = $zero1 - $zero2;
        return $time_c;
    }
}